package top.saymzx.easycontrol.app.helper;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
// adb shell pm grant top.saymzx.easycontrol.app android.permission.WRITE_SECURE_SETTINGS
public class MyAccessibilityService extends AccessibilityService {
    String TAG = "AliAccessibilityService";

    public static boolean accessibilityEnable=false;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.e("onAcEvent: ", event.getPackageName().toString());
        Log.e("onAcEvent: ", event.getClassName().toString());
        if (event.getPackageName().equals("com.android.systemui") && event.getClassName().equals("android.app.Dialog")) {
            AccessibilityNodeInfo nodeInfo = event.getSource();
            for (int i = 0; i < nodeInfo.getChildCount(); i++) {
                AccessibilityNodeInfo info = nodeInfo.getChild(i);
                Log.e("node",info.getClassName()+","+info.getText());
            }
            for (int i = 0; i < nodeInfo.getChildCount(); i++) {
                if (nodeInfo.getChild(i).getClassName().equals("android.widget.ScrollView")) {
                    for (int j = 0; j < nodeInfo.getChild(i).getChildCount(); j++) {
                        if (nodeInfo.getChild(i).getChild(j).getClassName().equals("android.widget.Button") && nodeInfo.getChild(i).getChild(j).getText().equals("确定")) {
                            Log.d(TAG, "onAccessibilityEvent: " + nodeInfo.getChild(i).getChild(j).getClassName() + ": " + nodeInfo.getChild(i).getChild(j).getText());
                            nodeInfo.getChild(i).getChild(j).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            return;
                        }
                    }
                }
            }
        }
    }

    //服务中断时的回调
    @Override
    public void onInterrupt() {
        Log.d(TAG, "onInterrupt");
    }
    
	/**
     * 获取应用程序名称
     */
    public static String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        accessibilityEnable=true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        accessibilityEnable=false;
    }
}
